var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    ifShowTips: true,
    ifShownoData: true,
    wOrderVo:"",
    countNum:0,//今日接单数
    totalPrice:0,//今日总金额
    buthiddenPrice:false,
    buthiddenTel: false,
    buthiddenCancel: false,
    userId:"",
    userInfo: null,
    code: "",
    //openId:"",
    wxType:"",
    orderStatus: [
      
      {
        "statusName": "进行中",
        "statusCode": 1
      },
      {
        "statusName": "所有订单",
        "statusCode": ""
      }

    ],

    statusSelect: 1,//判断是否选中
    pageIndex: 1
  },

  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) { 
      var that = this;
     
      // 登录
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          that.data.code = res.code;
          var code = res.code;
          wx.request({
            method: "POST",
            url: 'https://www.zaishengwang.com/wx/toCheckUser.do',
            dataType: 'json',
            header: {
              'content-type': 'application/x-www-form-urlencoded;',
            },
            data: {
              code: code,
            },
            success: function (res) {
              if (res.data.userVo == null) {
                app.globalData.openId = res.data.openId
                wx.reLaunch({
                  url: '../register/register',
                })
              } else {
                that.data.userId = res.data.userVo.bId;
                app.globalData.wxType = res.data.userVo.wxType;
                that.setData({wxType:app.globalData.wxType});
                wx.setStorageSync('userId', res.data.userVo.bId);
                var userId = wx.getStorageSync('userId');
                if (userId!="") {
                  app.globalData.userId = userId;
                  app.globalData.openId = res.data.openId;
                  that.setData({ ifShowTips: true });
                  that.onTodayInfo();
                  that.onOrderInfo();
                } else {
                  that.setData({ ifShowTips: false });
                }

              }
            },
            fail: function (error) {

            }
          })
        }
      })
    
    // var userId = wx.getStorageSync('userId');
  
    // that.setData({ userId: userId});
    // app.globalData.userId = userId;

    // 查看是否授权
    // wx.getSetting({
    //   success: function (res) {
    //     if (res.authSetting['scope.userInfo']) {
    //       // 已经授权，可以直接调用 getUserInfo 获取头像昵称
    //       wx.getUserInfo({
    //         success:function(res){
    //           console.log(res.userInfo);
    //         }
    //       })
    //     }
    //   }
    // })  


  },

  orderStatusList: function (e) {
    var that = this;
    that.setData({//把选中值放入判断值
      statusSelect: e.currentTarget.dataset.select,
      pageIndex: 1,
      wOrderVo: " ",
    })
    that.onOrderInfo();
  },



  /**
  * 生命周期函数--监听页面初次渲染完成
  */
  onReady: function () {
  
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  //扫一扫
  goscan: function(){

    wx.scanCode({
      success: (res) => {
        console.log("success",res);
        console.log(res.result);
        var userId = res.result;
        var receiptId = app.globalData.userId;
        if (userId.length == receiptId.length){
          wx.request({
            method: "POST",
            url: 'https://www.zaishengwang.com/wx/toScanOrder.do ',
            dataType: 'json',
            header: {
              'content-type': 'application/x-www-form-urlencoded;',
            },
            data: {
              userId: userId,
              receiptId: receiptId,
            },
            success: function (res) {
              console.log("receiptId", res);
              if (res.data.msg=="1"){
                wx.navigateTo({
                  url: 'scan?bId=' + res.data.orderVo.bId,
                })
              }else if (res.data.msg == "2") {
                wx.showModal({
                  title: '不符合该系统规定的用户！',
                  confirmColor: '#56BDE0',
                  showCancel: false,
                })
              }

            },
            fail: function (error) {
              console.log("error", error);
            }

          })
        }else{
          wx.showModal({
            title: '不符合该系统规定的二维码！',
            confirmColor: '#56BDE0',
            showCancel: false,
          })
        }
       

      },
      fail: (res) => {
        console.log("fail", res);
        wx.showModal({
          title: '不符合该系统规定的二维码！',
          confirmColor: '#56BDE0',
          showCancel: false,
        })
      }
    })

  },
  //二维码
  goCode: function () {

    wx.navigateTo({
      url: 'code',
    })

  },

  goSetting:function(){

    wx.navigateTo({
      url: '../mine/accountSetting',
    })
    
  },

  //今日接单，总金额请求接口

  onTodayInfo:function(){
    var that = this;
    wx.showLoading({
      title: '拼命加载中',
    })
    //进行中订单列表信息
    wx.request({
      method: "POST",
      url: 'https://www.zaishengwang.com/wx/toHomenCount.do',
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: {
        id: app.globalData.userId,
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.totalPrice == undefined) {
          that.setData({ countNum: res.data.countNum, totalPrice: 0 })
        }else {
          that.setData({ countNum: res.data.countNum, totalPrice: res.data.totalPrice })
        }
      },
      fail: function (error) {
      }
    })
  },

 //订单列表信息
  onOrderInfo: function () {
    var that = this;
    var arr = new Array;
    wx.request({
      method: "POST",
      url: 'https://www.zaishengwang.com/wx/serchReceiptOrderList.do',
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: {
        receiptId: app.globalData.userId,
        status: that.data.statusSelect,
        page: that.data.pageIndex,
        size: 8
      },
      success: function (res) {
        if (res.data.wOrderVo.length > 0) {
         
          for (var i = 0; i < res.data.wOrderVo.length; i++) {
            let createTime = res.data.wOrderVo[i].createTime.substring(0, 19);
            res.data.wOrderVo[i].createTime = createTime;
          }
          that.setData({ ifShownoData: true});
          // arr.push((res.data.wOrderVo));
          arr = res.data.wOrderVo;
         
        }else{

          that.setData({ ifShownoData: false });
        }
        if (that.data.pageIndex!=1){
          var array = that.data.wOrderVo;
          array = array.concat(arr);
          that.setData({ ifShownoData: true, wOrderVo: array});
        }else{
          that.setData({wOrderVo: arr}); 
        }
      },
      fail: function (error) {
      }
    })
  },

  bindGetUserInfo: function (e) {
    var that = this;
    that.setData({ ifShowTips: true });
    //使用
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.login({
            success: function (res) {
              var code = res.code;//登录凭证
              if (code) {
                //2、调用获取用户信息接口
                wx.getUserInfo({
                  success: function (res) {
                    var nickName = res.rawData.nickName;
                    var userImg = res.rawData.avatarUrl;
                    //3.请求自己的服务器，解密用户信息 获取unionId等加密信息
                    wx.request({
                      url: 'https://www.zaishengwang.com/',//自己的服务接口地址
                      method: 'post',
                      header: {
                        'content-type': 'application/x-www-form-urlencoded'
                      },
                      data: { 
                        code: code,
                        nickName: nickName,
                        userImg: avatarUrl
                      },
                      success: function (data) {

                        //4.解密成功后 获取自己服务器返回的结果
                        if (data.data.status == 1) {
                          var userInfo_ = data.data.userInfo;
                        } else {
                          console.log('解密失败')
                        }

                      },
                      fail: function () {
                        console.log('系统错误')
                      }
                    })
                  },
                  fail: function () {
                    console.log('获取用户信息失败')
                  }
                })

              } else {
                console.log('获取用户登录态失败！' + r.errMsg)
              }
            },
            fail: function () {
              console.log('登陆失败')
            }
          })

        } else {//即点击拒绝授权退出
          wx.navigateBack({
            delta: 1
          })
          console.log('获取用户信息失败')

        }

      }
    })

  },
  
//去定价事件
  toPriced: function (e) {
    var bId = e.currentTarget.dataset.bid;
    var that = this;
    that.setData({ buthiddenPrice: true});
    wx.navigateTo({
      url: 'priced?bId=' + bId,
      success: function (res) { that.setData({ buthiddenPrice: false });},
      fail: function (res) { that.setData({ buthiddenPrice: false }) },
      complete: function (res) { },
    })
  },
  
  //致电用户事件
  phonecallevent: function (e) {
    var that = this;
    // that.setData({ buthiddenTel: true });
    var tel = e.currentTarget.dataset.tel;
    wx.makePhoneCall({
      phoneNumber: tel
    })

  },
//取消订单事件
  ifCancel:function(e){
    var that = this;
    var bId = e.currentTarget.dataset.bid;
    
    wx.showModal({
     // title: '提示',
      content: '确定取消该订单吗？',
      cancelText:'再等等',
      confirmColor:'#50BEC5',
      success: function (res) {

        if (res.confirm) {
          that.setData({ buthiddenCancel: true });
          wx.request({
            method: "POST",
            url: 'https://www.zaishengwang.com/wx/updateOrderStatus.do',
            dataType: 'json',
            header: {
              'content-type': 'application/x-www-form-urlencoded',
            },
            data: {
              bId: bId,
              status: 3,
            },
            success: function (res) {
              if(res.data.msg != null){
                that.onOrderInfo();
                that.setData({ buthiddenCancel: false });
              }
            },
            fail: function (error) {
              that.setData({ buthiddenCancel: false });
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  //发布入口

  goFbSupply: function(){
    wx.navigateTo({
      url: '../supply/fb_supply',
    })
  },

  noScroll:function(){
//微信小程序有bind和catch两种事件绑定方法，bind事件绑定不会阻止冒泡事件向上冒泡，catch事件绑定可以阻止冒泡事件向上冒泡。我们使用catch绑定手指触摸事件，然后他的父节点就不会收到事件冒泡，这样就实现了禁止页面上下滑动
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    that.setData({
      pageIndex: 1, // 每次触发下拉事件pageIndex=1
      wOrderVo:"",
      ifShownoData:true,
    });
    that.onOrderInfo();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    that.setData({
      pageIndex: that.data.pageIndex + 1,
      ifShownoData: true,
    })
    // 上拉获取更多数据
    that.onOrderInfo();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }

})